package web;

import db.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import domain.Activity;
import domain.ActivityApplication;
import domain.Announcement;
import domain.Club;
import domain.ClubAdministrator;
import domain.ClubApplication;
import domain.SystemAdministrator;
import domain.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 管理员控制类
 *
 * @author zdc
 */
@Controller
@SessionAttributes({ "systemAdministrator" })
@RequestMapping("/systemAdministrator")

public class SystemAdministratorController {

    private static final RequestMethod[] PUT = null;
	@Autowired
    private SystemAdministratorRepository systemAdministratorRepository;
    @Autowired
    private ClubRepository clubRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ClubApplicationRepository clubApplicationRepository;
    @Autowired
    private ActivityRepository activityRepository;
    @Autowired
    private ActivityApplicationRepository activityApplicationRepository;
    @Autowired
    private ClubAdministratorRepository clubAdministratorRepository;
    
    /**
     * 系统管理员首页
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String showIndex(HttpSession session, Model model) {

        long clubAdministratorCount = clubAdministratorRepository.count();
        long userCount = userRepository.count();
        long clubCount = clubRepository.count();
        long activityCount = activityRepository.count();
        Date now = new Date();

        model.addAttribute("now",now );
        model.addAttribute("clubAdministratorCount", clubAdministratorCount);
        model.addAttribute("userCount", userCount);
        model.addAttribute("clubCount", clubCount);
        model.addAttribute("activityCount", activityCount);

        return "/systemAdministrator/index";
    }


	/**
	 * 查看系统管理员信息页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/checkInfo", method = GET)
    public String showAccountInfo(HttpSession session, Model model) {
        SystemAdministrator systemAdministrator = (SystemAdministrator) session.getAttribute("systemAdministrator");
        model.addAttribute("systemAdministrator", systemAdministrator);
        return "/systemAdministrator/checkInfo";
    }
	
	/**
	 *查看系统管理员信息修改页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/updateInfo", method = GET)
    public String showUpdateAccountInfo(HttpSession session, Model model) {
        SystemAdministrator systemAdministrator = (SystemAdministrator) session.getAttribute("systemAdministrator");
        model.addAttribute("systemAdministrator", systemAdministrator);
        return "/systemAdministrator/updateInfo";
    }
    
    /**
     * 提交系统管理员信息更新
     *
     * @param password
     * @param email
     * @param nickname
     * @param telephone
     * @return
     */
    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    public String updateAccountInfo(@RequestParam("password") String password,
                                    @RequestParam("nickname") String nickname,
                                    @RequestParam("email") String email,
                                    @RequestParam("telephone") String telephone,
                                    HttpSession session) {
        try {
            if (password.isEmpty()||nickname.isEmpty()){
                throw new Exception();
            }
            SystemAdministrator systemAdministrator = (SystemAdministrator) session.getAttribute("systemAdministrator");
            systemAdministrator.setPassword(password);
            systemAdministrator.setNickname(nickname);
            systemAdministrator.setEmail(email);
            systemAdministrator.setTelephone(telephone);
            systemAdministratorRepository.save(systemAdministrator);
            session.setAttribute("deleted", true);
        } catch (Exception e) {
            session.setAttribute("deleted", false);
        }
        return "redirect:/systemAdministrator/updateInfo";
    }


    /**
     * 获取user列表
     * @param keyword
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(value = "/users",method = GET)
    public String showUsers(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                            @RequestParam(value = "page", defaultValue = "1") int page,
                            HttpSession session, Model model) {
        List<User> allUsers = userRepository.findAll();
        List<User> userList = allUsers.stream()
               .filter(user -> user.getUsername().contains(keyword))
               .collect(Collectors.toList());
        model.addAttribute("userList", userList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (userList.size() + 9) / 10);
        return "/systemAdministrator/users";
    }
    

    /**
     * 删除一个用户
     * @param id 用户的ID
     * @return 删除成功页面
     */
    @RequestMapping(value = "/users/delete",method = POST)
    public String deleteUser(@RequestParam("id") int id, HttpSession session) {
        try{
            session.setAttribute("deleted",userRepository.deleteUserByUserID(id));
        }catch (Exception e){
            session.setAttribute("deleted", false);
        }
        return "redirect:/systemAdministrator/users";
    }

    /**
     * 获取club列表
     * @param keyword
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(value = "/clubs",method = GET)
    public String showClubs(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                            @RequestParam(value = "page", defaultValue = "1") int page,
                            HttpSession session, Model model) {
        List<Club> allClubs = clubRepository.findAll();
        List<Club> clubList = allClubs.stream()
               .filter(club -> club.getClubName().contains(keyword))
               .collect(Collectors.toList());
        model.addAttribute("clubList", clubList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (clubList.size() + 9) / 10);
        return "/systemAdministrator/clubs";
    }
    
    /**
     * 删除一个社团
     * @param id 社团的ID
     * @return 删除后的社团列表页面
     */
    @RequestMapping(value = "/clubs", method = POST)
    public String deleteClubs(@RequestParam("id") int id) {
        clubRepository.deleteClub(id);
        return "redirect:/systemAdministrator/clubs";
    }
    
    /**
     * 审批社团
     * @param keyword
     * @param page
     * @return 社团申请页面
     */
    @RequestMapping(value = "/clubApplications", method = GET)
    public String showClubApplications(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                                       @RequestParam(value = "page", defaultValue = "1") int page,
                                       HttpSession session, Model model) {
        List<ClubApplication> allApplications = clubApplicationRepository.findAll();
        List<ClubApplication> applicationList;
        if (keyword == null || keyword.isEmpty()) {
            applicationList = allApplications;
        } else {
            applicationList = allApplications.stream()
                    .filter(application -> application.getPendingClub() != null && application.getPendingClub().getClubName() != null && application.getPendingClub().getClubName().contains(keyword))
                    .collect(Collectors.toList());
        }
        model.addAttribute("clubApplicationList", applicationList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (applicationList.size() + 9) / 10);
        return "/systemAdministrator/clubApplications";
    }
    

    @RequestMapping(value = "/clubApplications/pass", method = POST)
    public String passClubApplication(@RequestParam("id") int id) {
        ClubApplication application = clubApplicationRepository.findOne(id);
        if (application != null) {
            application.setStatus(1);
            clubApplicationRepository.updateClubApplication(application);
            Club club = application.getPendingClub();
            clubRepository.save(club);
//            int clubApplicationID = application.getClubApplicationID();
//            clubApplicationRepository.deleteClubApplication(clubApplicationID);
        }
        return "redirect:/systemAdministrator/clubApplications";
    }

    @RequestMapping(value = "/clubApplications/rejected", method = POST)
    public String rejectClubApplication(@RequestParam("id") int id) {
        ClubApplication application = clubApplicationRepository.findOne(id);
        if (application != null) {
            application.setStatus(-1);
            int clubApplicationID = application.getClubApplicationID();
            clubApplicationRepository.deleteClubApplication(clubApplicationID);
        }
        return "redirect:/systemAdministrator/clubApplications";
    }

    /**
     * 审批社团活动
     * @param keyword
     * @param page
     * @return 申请列表页面
     */
    @RequestMapping(value = "/activityApplications", method = GET)
    public String showActivityApplications(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                                           @RequestParam(value = "page", defaultValue = "1") int page,
                                           HttpSession session, Model model) {
        List<ActivityApplication> allApplications = activityApplicationRepository.findAll();
        List<ActivityApplication> applicationList;
        if (keyword == null || keyword.isEmpty()) {
            applicationList = allApplications;
        } else {
            applicationList = allApplications.stream()
                    .filter(application -> application.getPendingActivity() != null && application.getPendingActivity().getActivityName() != null && application.getPendingActivity().getActivityName().contains(keyword))
                    .collect(Collectors.toList());
        }
        model.addAttribute("activityApplicationList", applicationList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (applicationList.size() + 9) / 10);
        return "/systemAdministrator/activityApplications";
    }

    @RequestMapping(value = "/activityApplications/pass", method = POST)
    public String passActivityApplication(@RequestParam("id") int id) {
        ActivityApplication application = activityApplicationRepository.findOne(id);
        if (application != null) {
            application.setStatus(1);
            activityApplicationRepository.updateActivityApplication(application);
            Activity activity = application.getPendingActivity();
            activityRepository.save(activity);
//            int activityApplicationID = application.getActivityApplicationID();
//            activityApplicationRepository.deleteActivityApplication(activityApplicationID);
        }
        return "redirect:/systemAdministrator/activityApplications";
    }

    @RequestMapping(value = "/activityApplications/rejected", method = POST)
    public String rejectActivityApplication(@RequestParam("id") int id) {
        ActivityApplication application = activityApplicationRepository.findOne(id);
        if (application != null) {
            application.setStatus(-1);
            activityApplicationRepository.updateActivityApplication(application);
//            int activityApplicationID = application.getActivityApplicationID();
//            activityApplicationRepository.deleteActivityApplication(activityApplicationID);
        }
        return "redirect:/systemAdministrator/activityApplications";
    }
    
    /**
     * 查看活动
     * @param keyword
     * @param page
     * @param model Model对象
     * @return 社团活动列表页面
     */
    @RequestMapping(value = "/activities", method = GET)
    public String showActivities(@RequestParam(value = "keyword", defaultValue = "") String keyword,
                                 @RequestParam(value = "page", defaultValue = "1") int page,
                                 HttpSession session, Model model) {
        List<Activity> allActivities = activityRepository.findAll();
        List<Activity> activityList = allActivities.stream()
               .filter(activity -> activity.getActivityName().contains(keyword))
               .collect(Collectors.toList());
        model.addAttribute("activityList", activityList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPage", (activityList.size() + 9) / 10);
        return "/systemAdministrator/activities";
    }
    
    /**
     * 删除一个活动
     * @param id
     * @return 删除后的活动列表页面
     */
    @RequestMapping(value = "/activities/delete", method = POST)
    public String deleteActivities(@RequestParam("id") int id) {
        activityRepository.deleteActivity(id);
        return "redirect:/systemAdministrator/activities";
    }

    /**
     * 退出登录
     *
     */
    @RequestMapping(value = "/logout", method = GET)
    public String logout(HttpSession session) {
        session.removeAttribute("systemAdministrator");
        session.invalidate();
        return "redirect:/";
    }

    @RequestMapping(value = "/userInfo", method = GET)
    public String showUserInfo(@RequestParam(value = "userID") int userid, Model model){
        User user = userRepository.findOne(userid);
        model.addAttribute("userinfo",user);
        return "/systemAdministrator/userInfo";
    }

    /**
     * 提交用户信息更新
     *
     * @param password
     * @param email
     * @param nickname
     * @param telephone
     * @param gender
     * @param college
     * @param model
     * @return
     */
    @RequestMapping(value = "/userInfo", method = POST)
    public String updateUserInfo(@RequestParam(value = "password") String password,
                         @RequestParam(value = "email") String email,
                         @RequestParam(value = "nickname") String nickname,
                         @RequestParam(value = "telephone") String telephone,
                         @RequestParam(value = "gender") String gender,
                         @RequestParam(value = "college") String college,
                         @RequestParam(value = "studentID") String studentID,
                         @RequestParam(value = "username") String username,
                         HttpSession session, Model model) {
        try {
            if (password.isEmpty()||nickname.isEmpty()||college.isEmpty()||studentID.isEmpty()){
                throw new Exception();
            }
            User user = userRepository.findByUserName(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setNickname(nickname);
            user.setTelephone(telephone);
            user.setGender(Objects.equals(gender, "true"));
            user.setCollege(college);
            user.setStudentID(studentID);
            userRepository.update(user);
            session.setAttribute("deleted", true);
            model.addAttribute("userinfo",user);
        } catch (Exception e) {
            session.setAttribute("deleted", false);
        }
        return "/systemAdministrator/userInfo";
    }

    @RequestMapping(value = "/clubInfo", method = GET)
    public String showClubInfo(@RequestParam(value = "clubID") int clubID, Model model){
        Club club = clubRepository.findOne(clubID);
        model.addAttribute("clubinfo",club);
        return "/systemAdministrator/clubInfo";
    }

    @RequestMapping(value = "/clubInfo", method = POST)
    public String updateClubInfo(@RequestParam("clubName") String clubName,
                                 @RequestParam("college") String college,
                                 @RequestParam("description") String description,
                                 HttpSession session, Model model) {
        try {
            if (college.isEmpty()||description.isEmpty()){
                throw new Exception();
            }
            Club club = clubRepository.findByClubName(clubName);
            if (club != null) {
                club.setCollege(college);
                club.setDescription(description);
                clubRepository.updateClub(club.getClubID(),club.getClubName(),
                        club.getCollege(),club.getDescription(),
                        club.getCreateTime());
            }
            model.addAttribute("clubID",club.getClubID());
            session.setAttribute("deleted", true);
        } catch (Exception e) {
            session.setAttribute("deleted", false);
        }
        return "redirect:/systemAdministrator/clubInfo";
    }
}
